<?php
header("Content-type:text/html;charset=UTF-8");
require_once 'Conn.php';
$db->query("SET NAMES utf8");

function checkInput($data)
{
    $data = trim($data);
    $data =stripslashes($data);
    $data =htmlspecialchars($data);
    return $data;   
}

//获取学号
$stuNo = checkInput($_POST['stuNo']);
if(empty($stuNo)){
    echo"<script>alert('学号没有填写!');history.go(-1);</script>";
    exit();
}
//检查学号是否已经存在
$sql = "SELECT * FROM Student WHERE StudentID='$stuNo'";
$result = $db->query($sql);
if ($result->num_rows >0){
    echo"<script>alert('该学号已经存在');history.go(-1);</script>";
    exit();
}
//获取姓名
$stuName = checkInput($_POST['stuName']);
if(empty($stuName)){
    echo"<script>alert('姓名没有填写！');history.go(-1);</script>";
    exit();
}
//获取密码
$password = checkInput($_POST['pwd']);
if(empty($password)){
    echo"<script>alert('密码没有填写！');history.go(-1);</script>";
    exit();
}
//获取班级
$className = checkInput($_POST['className']);
//获取性别
$sex = checkInput($_POST['sex']);
//获取爱好
if(array_key_exists('hobby',$_POST)){
    $hobby = join('，',$_POST['hobby']);
}else{
    $hobby='';
}
//获取手机
$mobile = checkInput($_POST['mobile']);
//获取邮箱
$email = checkInput($_POST['email']);
//处理相片上传
switch($_FILES['photo']['error']){
    case 0://成功上传
        $ftypes = ['image/gif','image/pjpeg','image/jpeg','image/x-png'];//要求的文件类型
        $type = $_FILES['photo']['type'];//上传文件的文件类型
        if(in_array($type,$ftypes)){//上传文件是指定的类型
            $fname= $_FILES['photo']['name'];//文件名
            //避免文件重名，将文件名改为以学号命名
            $tmp=explode('.',$fname);//将文件名以','分割得到后缀名，得到一个数组
            $newFname=$stuNo . '.' .$tmp[1];
            $destination = 'Upload/' .$newFname;
            move_uploaded_file($_FILES['photo']['tmp_name'],$destination);
        }else{
            echo"<script>alert('上传文件类型不符合要求！');history.go(-1);</script>";
    exit();
        }
        break;
        case 1://文件大小超过PHP默认的限制2M
            echo"<script>alert('上传文件出错，文件大小超过了限制！');history.go(-1);</script>";
    exit();
    case 4://没有选择上传文件
        $destination= '';
        break;
}
$sql="INSERT INTO Student VALUES('$stuNo','$stuName','$password','$className','$sex','$hobby','$mobile','$email','$destination')";
echo $sql;
$result =$db->query($sql);
if($result){
    //echo"<script>alert('注册成功！');history.go(-1);</script>";
    echo"<script>alert('注册成功！');</script>";
}else{
    echo"<script>alert('注册失败!');history.go(-1);</script>";
}
?>